import { Injectable, Inject } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
import { Cache } from 'cache-manager';
import { CACHE_MANAGER } from '@nestjs/cache-manager';

@Injectable()
export class UserService {
  constructor(
    private readonly httpService: HttpService,
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
  ) {}

  private readonly USER_SERVICE_URL = 'http://localhost:3001/api';

  async getUserProfile(userId: string) {
    const cacheKey = `user_profile_${userId}`;
    const cacheData = await this.cacheManager.get(cacheKey);

    if (cacheData) {
      return cacheData;
    }

    try {
      const response = await firstValueFrom(
        this.httpService.get(`${this.USER_SERVICE_URL}/users/${userId}`),
      );
       // 缓存用户数据， 设置TTL为5分钟
      await this.cacheManager.set(cacheKey, response.data, 300000);
      return response.data;
    } catch (error) {
      throw new Error('Failed to fetch user profile');
    }
  }

  async getUserOrders(userId: string) {
    // 这里聚合用户信息和订单信息
    const [userProfile, orders] = await Promise.all([
      this.getUserProfile(userId),
      this.getUserOrderFromOrderService(userId),
    ]);
    return {
      user: userProfile,
      orders,
    }
  }

  private async getUserOrderFromOrderService(userId: string) {
    try {
      const response = await firstValueFrom(
        this.httpService.get(`${this.USER_SERVICE_URL}/orders/${userId}`),
      );
      return response.data;
    } catch (error) {
      throw new Error('Failed to fetch user orders');
    }
  }
}
